package view
{
	import com.bit101.components.HBox;
	import com.bit101.components.ImageSlider;
	import com.bit101.components.Slider;
	import com.liu.load.DataLoader;
	import com.liu.load.LoadInfo;
	import com.liu.load.LoadManager;
	
	import events.BitmapEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.net.URLRequest;
	
	import models.ModelLocator;
	
	public class HCanvas extends Sprite
	{
		private var hslider:ImageSlider;
		private var hbox:HBox;
		private var maskShape:Shape;
		private var viewW:int = 355;
		private var viewH:int = 95;
		public function HCanvas()
		{
			init();
		}
		private function init():void{
			maskShape = new Shape;
			maskShape.graphics.beginFill(0xff0000);
			maskShape.graphics.drawRect(0,0,viewW,viewH);
			maskShape.graphics.endFill();
			this.addChild(maskShape);
			
			hslider = new ImageSlider(Slider.HORIZONTAL,this,40,90);
			hslider.width = 275;
			hbox = new HBox(this);
			hbox.mask = maskShape;
			hslider.addEventListener(Event.CHANGE,onChange);
		}
		public function set source(value:Array):void{
			for(var i:int;i<value.length;i++){
				var img:DataLoader = new DataLoader();
				img.load(new URLRequest(ModelLocator.getInstance().root + value[i].url));
				img.data = value[i];
				hbox.addChild(img);
				img.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaded);
				img.addEventListener(MouseEvent.CLICK,onClick);
			}
			hslider.step = 100/value.length;
		}
		private function onLoaded(event:Event):void{
			Loader(event.target.loader).dispatchEvent(new Event(Event.RESIZE));
			var img:DataLoader = DataLoader(event.target.loader);
			var sc:Number = img.width/87;
			if(sc>1){
				img.scaleX = img.scaleY = 1/sc;
			}
		}
		private function onChange(event:Event):void{
			trace(event.target.value)
			hbox.x = (viewW - hbox.width)*event.target.value/100;
		}
		private function onClick(event:MouseEvent):void{
			var evt:BitmapEvent = new BitmapEvent(BitmapEvent.BITMAPEVENT);
			var bitmap:Bitmap = Loader(event.target).contentLoaderInfo.content as Bitmap;
			
			var bitmapdata:BitmapData = new BitmapData(DataLoader(event.target).data.orgW,DataLoader(event.target).data.orgH,true,0)
				//bitmap.bitmapData.clone();
			var ma:Matrix = new Matrix;
			var sx:Number =  DataLoader(event.target).data.orgW/bitmap.width;
			ma.scale(sx,sx);
			bitmapdata.draw(bitmap,ma);
			bitmap = new Bitmap(bitmapdata);
			evt.bitmap = bitmap;
			var data:Object = ModelLocator.getInstance().currentdata;
			evt.scale = data.w/data.orgW;
			evt.url = DataLoader(event.target).data.url2 as String;
			this.parent.dispatchEvent(evt);
		}
	}
}